package edu.nuist.shixun.api.user;

import edu.nuist.shixun.table.User;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j   //注解不是必须的, 让当前类可以用log对象打印日志
@CrossOrigin // 是必须, 让当前服务允许被跨域请求
@RestController // 是必须, 声明当前类为一个HTTP服务类



    public class UserLoginApi {

        // 组合数据库编程对象
        @Resource
        JdbcTemplate jdbcTemplate;

        @PostMapping("/user/login")
        public Object login(String account, String password) {
            log.info(String.format("进入系统登录服务,接收到账号:%s,密码:%s", account,password));
            log.info("编写SQL语句, 根据账号account查询账户信息");
            String sql = "select id,account,password,role,status from user where account=?";
            log.info("执行SQL语句");
            List<User> userList = jdbcTemplate.query(sql, new Object[]{account}, new RowMapper<User>(){
                @Override
                public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                    User user = new User();
                    user.setId(rs.getInt("id"));
                    user.setAccount(rs.getString("account"));
                    user.setPassword(rs.getString("password"));
                    user.setRole(rs.getString("role"));
                    user.setStatus(rs.getInt("status"));
                    return user;
                }
            });
            Map map = new HashMap();
            log.info("根据集合是否为空判断账户是否存在");
            if (userList.isEmpty()) {
                map.put("code", "-1");
                map.put("message", "账户不存在!");
                return map;
            }
            log.info("取出集合中的第一个用户");
            User user = userList.get(0);
            if (user.getStatus() != 0) {
                map.put("code", "-1");
                map.put("message", "账户状态异常!");
                return map;
            }
            if (!password.equals(user.getPassword())) {
                map.put("code", "-1");
                map.put("message", "密码错误!");
                return map;
            }
            map.put("code", "1");
            map.put("message", "登录成功!");
            map.put("data", user);
            return map;
        }

    }


